package roborally.script.conditionalCommand;

import exception.IllegalScriptSyntaxException;
import roborally.model.Robot;
import roborally.script.Command;
import roborally.script.Condition;
import roborally.script.ConditionalCommand;
import be.kuleuven.cs.som.annotate.*;
import be.kuleuven.cs.som.taglet.*;

/**
 * @author Joren VERSPEURT
 * @author Mathieu REYMOND
 * @version 3.0
 * 
 * The class representing an If statement in the RoboRally script language.
 */
public class If extends ConditionalCommand {
	
	/**
	 * Create a new If with a given Robot, Condition and 2 Commands, the first of which is the "then" Command, the second the "else" Command.
	 * @param robot The Robot this If will apply to.
	 * @param condition The Condition that applies to this If.
	 * @param commands The 2 commands that belong to this If statement
	 * @throws IllegalScriptSyntaxException If the number of Commands given is not 2. 
	 */
	public If(Robot robot, Condition condition, Command... commands) throws IllegalScriptSyntaxException {
		super(robot, condition, commands);
		if(getCommands().size() != 2) {
			throw new IllegalScriptSyntaxException("You must have 2 commands in an if-command");
		}
	}
	
	/**
	 * If the condition for this If is true execute the first given command, else execute the second.
	 */
	@Override
	public void step() {
		if(condition.isTrue()) {
			getCommands().get(0).step();
			if(getCommands().get(0).isExecuted()) setExecuted(true);
		}
		else {
			getCommands().get(1).step();
			if(getCommands().get(1).isExecuted()) setExecuted(true);
		}
	}
	
	/**
	 * Sets the If's executed state to <code>state</code> and also the executed states of the 2 sub-Commands.
	 */
	@Override
	public void setExecuted(boolean state) {
		for(Command command : getCommands()) {
			command.setExecuted(state);
		}
		super.setExecuted(state);
	}
	
	/**
	 * The script word for this command.
	 */
	@Override
	public String toString() {
		return "if";
	}
}
